/*
 * @lc app=leetcode.cn id=289 lang=javascript
 *
 * [289] 生命游戏
 */

// @lc code=start

/**
 * @param {number[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
var gameOfLife = function (board) {
  const row = board.length;
  const col = board[0].length;

  const directions = [
    [-1, -1],
    [-1, 0],
    [-1, 1],
    [0, -1],
    [0, 1],
    [1, -1],
    [1, 0],
    [1, 1],
  ];

  // 计算下一个状态
  for (let i = 0; i < row; i++) {
    for (let j = 0; j < col; j++) {
      let liveNeighbors = 0;
      for (const [dx, dy] of directions) {
        const x = i + dx;
        const y = j + dy;
        if (
          x >= 0 &&
          x < row &&
          y >= 0 &&
          y < col &&
          (board[x][y] === 1 || board[x][y] === -1)
        ) {
          liveNeighbors++;
        }
      }

      if (board[i][j] === 1 && (liveNeighbors < 2 || liveNeighbors > 3)) {
        board[i][j] = -1; // 活细胞死亡
      }
      if (board[i][j] === 0 && liveNeighbors === 3) {
        board[i][j] = 2; // 死细胞复活
      }
    }
  }

  // 更新原始 board
  for (let i = 0; i < row; i++) {
    for (let j = 0; j < col; j++) {
      if (board[i][j] === -1) board[i][j] = 0;
      else if (board[i][j] === 2) board[i][j] = 1;
    }
  }
};
// @lc code=end
